const cmds = require('./cmd.js');
function blue_list(func) {
  wx.openBluetoothAdapter({
    success: function (res) {
      //开启适配器状态监听(全局)
      adapterStatusChange();
      //开启搜索
      startDiscovery();
      _blu_list();
    },
    fail: function () { wx.showToast({ title: '请先启用蓝牙功能！',icon:"loading" }) },
    complete: function () {
      console.log("blue_list success");
    }
  });
}
//适配器状态监听
function adapterStatusChange() {
  wx.onBluetoothAdapterStateChange(function (res) {
    if (res.available) {
      getApp().globalData.blue_adapter_able = true;
    } else {
      getApp().globalData.blue_adapter_able = false;
    }
  });
}
//开启搜索
function startDiscovery() {
  //延迟的作用确保上面的代码执行完了
  setTimeout(function () {
    if (!getApp().globalData.blue_discovering) {
      wx.startBluetoothDevicesDiscovery({
       // services: getApp().globalData.able_serviceIds,
        success: function (res) {
          getApp().globalData.blue_discovering = true;
        },
      })
    }
  }, 80);
}
//停止搜索
function stopDiscovery() {
  wx.stopBluetoothDevicesDiscovery({
    success: function (res) {
      getApp().globalData.blue_discovering = false;
    },
  })
}

//获取蓝牙列表
function _blu_list() {
  setTimeout(function () {
    //获取设备
    wx.getBluetoothDevices({
      success: function (res) {        
        wx.setStorageSync("device_list", res.devices);//同步设备列表
      },
    })
    //监听新的设备
    wx.onBluetoothDeviceFound(function (res) {
      wx.getBluetoothDevices({
        success: function (res) {                   
          wx.setStorageSync("device_list", res.devices);//同步设备列表
        },
      })
    })
  }, 150);
}

//开启连接
function blue_con(deviceId) {
  var that=this;
  if (deviceId == null || deviceId.length < 5) { wx.showToast({ title: '设备', }); return false; }
  //关闭其它连接
  blue_close();
  //确保链接关闭才开启
  setTimeout(function () {
    if (!getApp().globalData.blue_is_connectd) {//如果链接状态是没有链接
      wx.createBLEConnection({
        deviceId: deviceId,
        success: function (res) {
          //设置当前连接id       
          getApp().globalData.current_con_deviceId = deviceId;
          getApp().globalData.blue_is_connectd = true;
          console.log("连接成功");

          //开启异常链接监听
          wx.onBLEConnectionStateChange(function (e) {
            console.log('device ' + e.deviceId + ' state has changed, connected: ' + e.connected);
            if (!e.connected) {
              getApp().globalData.current_con_deviceId = null;
              getApp().globalData.blue_is_connectd = false;
              wx.showToast({ title: '连接断开', });
            } else {
              getApp().globalData.current_con_deviceId = deviceId;
              getApp().globalData.blue_is_connectd = true;
            }
          });
          //监听notify
          blue_notify(deviceId);
        },
        fail: function (res) { console.log("连接失败", res); },
        complete: function () { stopDiscovery(); }  //关闭搜索
      })
    }
  }, 100);
}
//关闭连接
function blue_close() {
  var deviceId = getApp().globalData.current_con_deviceId;
  if (deviceId == null || deviceId.length < 5) {
    return false;
  }
  wx.closeBLEConnection({
    deviceId: deviceId,
    success: function (res) {
      //下面2行的值 由onBLEConnectionStateChange 监听来改变
      //因为连续点击2次连接的时候再次点击关闭连接时候关闭无效
      // getApp().globalData.current_con_deviceId = null;
      // getApp().globalData.blue_is_connectd=false;
      console.log("停止closeBLEConnection--success");
    },
    fail: function (res) {
      console.log("停止closeBLEConnection--fail", res);
    }
  })
}

//发送指令
function blue_write(set1) {
  var deviceId = getApp().globalData.current_con_deviceId;
  var serviceId = getApp().globalData.current_con_serviceId[0];
  if (deviceId == null || deviceId == '') {
    wx.showToast({ title: '蓝牙连接已经断开', icon: "loading" });
    return false;
  }

  var charset_write = getApp().globalData.charset_write[0];
  var charset_notify = getApp().globalData.charset_notify[0];
  //封装数据  
  var cmd = set1;
  //管道写值
  wx.writeBLECharacteristicValue({
    deviceId: deviceId,
    serviceId: serviceId,
    characteristicId: charset_write,
    value: cmd,
    success: function (res) {
      console.log("发送指令成功1：", res);
    },
    fail: function (res) { console.log("发送指令失败:", res); }
  })
}
//接收通知
function blue_notify(deviceId) {
  var serviceId = getApp().globalData.current_con_serviceId[0];
  var charset_notify = getApp().globalData.charset_notify[0];
  var charset_write = getApp().globalData.charset_write[0];
  //获取服务（一定要运行 否者报1004）
  wx.getBLEDeviceServices({
    deviceId: deviceId,
    success: function (res) {
      wx.getBLEDeviceCharacteristics({
        deviceId: deviceId,
        serviceId: serviceId,
        success: function (e) {
          console.log("获取charset 成功", e);
          //notifyBLECharacteristicValueChange 的监听
          wx.notifyBLECharacteristicValueChange({
            state: true, // 启用 notify 功能
            // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
            deviceId: deviceId,
            // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
            serviceId: serviceId,
            // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
            characteristicId: charset_notify,
            success: function (res) {
              console.log('charset_notify success:', res);
            },
            fail: function (res) { console.log("charset_notify error:", charset_notify, res) },
            complete: function () { console.log("charset_notify complete"); }
          });



          //onBLECharacteristicValueChange 监听
          wx.onBLECharacteristicValueChange(function (characteristic) {
            console.log('characteristic value changed:', characteristic);
            var buffer = characteristic.value;
            var dataView = new DataView(buffer);
            if (characteristic.characteristicId == charset_write) {
              var len = buffer.byteLength;
              for (var i = 0; i < len; i++) {
                console.log("charset_write change:", i, dataView.getUint8(i));
              }
            } else if (characteristic.characteristicId == charset_notify) {
              var len = buffer.byteLength;
              if (len > 2) {
                cmds.gets(buffer);
              }
              for (var i = 0; i < len; i++) {
                console.log("charset_notify change:", i, dataView.getUint8(i));
              }
            } else {              
              console.log("检查是  null");
            }
          });
        },
        fail: function (e) {
          console.log("获取charset 失败--", e, deviceId, serviceId);
        }
      })
    },
    fail: function (res) {
      console.log("getBLEDeviceServices---fail", res);// 这个可以判断蓝牙断开      
    }
  });
}
//读取管道的值
function blue_read(characteristicId) {
  var deviceId = getApp().globalData.current_con_deviceId[0];
  var serviceId = getApp().globalData.current_con_serviceId[0];
  if (deviceId == null || deviceId == '') {
    wx.showToast({
      title: '未链接设备',
    })
    return;
  }
  wx.readBLECharacteristicValue({
    deviceId: deviceId,
    serviceId: serviceId,
    characteristicId: characteristicId,
    success: function (res) {
      console.log("读取管道的值--success", res);
    },
    fail: function (res) {
      console.log("读取管道的值--fail", res);
    }
  })
}
//读取心率数据

module.exports = {
  blue_list: blue_list,
  blue_close: blue_close,
  blue_con: blue_con,
  blue_write: blue_write,
  blue_read: blue_read
}